<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>

<body>
  <!-- 准备好一个容器-->
  <div id="app">
    <h2>学生搜索</h2>
    <input type="text" placeholder="请输入名字：" v-model="keyWord"/><br/>
    <button @click="sortType=2">年龄升序</button>
    <button @click="sortType=1">年龄降序</button>
    <button @click="sortType=0">原始顺序</button>
    <ul>
      <li v-for="student of myStudents1" :key="student.id">
        {{student.id}}--{{student.name}}--{{student.age}}
      </li>
    </ul>
  </div>
  <script src="vue.js"></script>
  <script>
    Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。
    //创建vue实例
    new Vue({
      el: '#app',
      data: {
        students: [
          {id: 1, name: '张三', age: 23},
          {id: 2, name: '李四', age: 23},
          {id: 3, name: '王五', age: 23},
          {id: 4, name: '赵六1', age: 23},
          {id: 5, name: '赵六2', age: 53},
        ],
        keyWord: '',
        myStudents: [], //存放查询出来的符合条件的学生
        sortType: 0 // 0:原始顺序 1：降序 2：升序
      },
      computed: {
        //计算属性get函数什么时候调用：
        //（1）初次读取时候会执行一次
        //（2）当依赖的数据发生改变时会被再次调用
        myStudents1() {
          let arr = this.students.filter(student =>  student.name.indexOf(this.keyWord) != -1);
          arr.sort((student1, student2) => {
            //降序：后减前
            if (this.sortType == 1) {
              return student2.age - student1.age;
            } else if (this.sortType == 2) {
              return student1.age - student2.age;
            } else {
              return 0;
            }
          });

          return arr;
        }
      }
    })
  </script>
</body>

</html>